#!/usr/bin/perl -w

use strict;


# Check arguments
if (@ARGV == 0) {
    die "Need file name as argument\nUsage: $0 file\n";
}


# Read the file
my $filename = $ARGV[0];
open FILE, $filename or die "Couldn't open file '$filename': $!\n";
my @lines = <FILE>;
close FILE or warn "Problems closing file '$filename': $!\n";

if (scalar(@lines) != 9) {
    die "Unexpected number of lines in board. Expected 9 lines.\n";
}
chomp @lines;


my @squares;


# Parse the cwb format

my $square_nbr = 0;
for (my $line_nbr = 0; $line_nbr < 8; $line_nbr++) {
    my $line = $lines[$line_nbr];
    $line =~ s/^\s+|\s+$//g;

    my @tokens = split /\s+/, $line;

    if (scalar(@tokens) != 4) {
        die 'Unexpected number of tokens on line ', $line_nbr + 1,
            '. Expected 4 tokens, got ', scalar(@tokens),
            ': (', join(', ', @tokens), ").\n";
    }

    foreach my $token (@tokens) {
        if ($token =~ /^[bBwW\-]$/) {
            $token =~ s/-/./;
            $squares[$square_nbr] = $token;
        } else {
            die "Unexpected token '$token'. Expected one of -, b, B, w, or W\n";
        }

        $square_nbr++;
    }
}

if ($lines[8] =~ /^\s*([bBwW])\s*$/) {
    $squares[32] = lc $1;
} else {
    die "Unexpected turn line '$lines[8]'. Expected one of b, B, w, or W\n";
}


# Print out in wdp format
for (my $row = 0; $row < 8; $row++) {
    my $from = $row * 4;
    my $to = $from + 3;
    printf '%s%s%s%s ', @squares[$from .. $to];
}
print $squares[32], "\n";
